<template>
	<basic-container>
		<avue-crud
			:option="option"
			:data="data"
			ref="crud"
			:table-loading="loading"
			:page="page"
			@refresh-change="refreshChange"
			@search-change="searchChange"
			@search-reset="searchReset"
			@current-change="currentChange"
			@size-change="sizeChange"
			@on-load="onLoad"
		>
			<template slot-scope="{ row }" slot="goodsSoRange">
				<el-button size="mini" type="text" style="color: #606266;" @click="handleRowClick(0,row)">点击查看</el-button>
			</template>
			<template slot-scope="{ row }" slot="applyAreas">
				<el-button size="mini" type="text" style="color: #606266;" @click="handleRowClick(1,row)">点击查看</el-button>
			</template>
			<template slot-scope="{ row }" slot="goodsMainPhotoUrl">
				<img :src="row.goodsMainPhotoUrl" style="width:50px;height:50px;" />
			</template>
			<template slot-scope="scope" slot="menu">
				<el-button type="text" size="mini" v-if="scope.row.bpmApplyStatus == 4" @click="editArea(scope.row)">修改区域</el-button>
			</template>
		</avue-crud>
		<el-dialog title="选择区域" :visible.sync="dialogVisibleEditArea" width="30%">
			<el-tree :data="treeData" ref="tree" show-checkbox node-key="id" :props="defaultProps" :default-expand-all="false" @check="handleCheckChange"></el-tree>
			<span slot="footer" class="dialog-footer">
				<el-button @click="cancel">取 消</el-button>
				<el-button type="primary" @click="submitEdit">确 定</el-button>
			</span>
		</el-dialog>
		<el-dialog
		  :title="showTitle"
		  :visible.sync="currentGoodsVis"
		  width="40%"
		  center>
		  <span style="padding: 20px;color: #000;">{{currentGoodsName}}</span>
		  <div style="padding: 20px;max-height: 300px;overflow: scroll;line-height: 30px;">
			<el-tree :data="currentAreas" :default-expanded-keys="[]" node-key="id" accordion ref="goodsClassTree" highlight-current :props="propsClass"></el-tree>
		  </div>
		</el-dialog>
	</basic-container>
</template>
<script>
	import {getOrganizationTreeNodeByIds } from '@/api/base/goods/goods';
import { getList, getGoodsSoRangeTree, editGoodsSoRange } from '@/api/base/store/checkCross.js';
import { getOrganizationMapByLevel } from '@/api/base/goods/addGoods';
var Dict = JSON.parse(localStorage.getItem('mall-dictionary')).content;
export default {
	data() {
		return {
			addSoRangeOrganization:[],//选中的区域
			delSoRangeOrganization:[],//未选中的区域
			propsClass: {
				label: 'name',
				id: 'id',
				children: 'childrenNodes',
			},
			currentGoodsVis:false,
			currentGoodsName:'',
			currentAreas:[],
			showTitle:'',
			query: {},
			loading: true,
			page: {
				pageSize: 10,
				currentPage: 1,
				total: 0
			},
			dialogVisibleEditArea: false,
			treeData: [],
			currentUserOrganizationId: '',
			defaultProps: {
				children: 'childrenNodes',
				label: 'name'
			},
			checkeddataIds: [],
			checkeddataStr: [],
			obj: {},
			data: [
				{
					storeName: 'aaa'
				},
				{
					storeName: 'bbb'
				}
			],
			editData: {},
			option: {
				border: true,
				page: false,
				align: 'center',
				menuAlign: 'center',
				menuType: 'button',
				editBtn: false,
				delBtn: false,
				addBtn: false,
				fit: true,
				column: [
					{
						label: '店铺名称',
						prop: 'storeName',
						search: true
					},
					{
						label: '商品名称',
						prop: 'goodsName',
						search: true
					},
					{
						label: '商品图片',
						slot: true,
						prop: 'goodsMainPhotoUrl'
					},
					{
						label: '商城售价(￥)',
						prop: 'showPrice'
					},
					{
						label: '累计销量',
						prop: 'saleNum'
					},
					{
						label: '累计销售额',
						prop: 'saleAmount'
					},
					{
						label: '佣金额',
						prop: 'showCommissionValue'
					},
					{
						label: '状态',
						prop: 'bpmApplyStatus',
						search: true,
						dicData: Dict.BPM_APPLY_STATUS_ENUM,
						type: 'select',
						props: {
							label: 'label',
							value: 'value'
						}
					},
					{
						label: '商品已可见范围',
						prop: 'goodsSoRange',
						slot:true,
					},
					{
						label: '审核开通的可见范围',
						prop: 'applyAreas',
						slot:true,
					}
				]
			},
			fourLevel:[]
		};
	},
	created() {
		getOrganizationMapByLevel({level:4}).then(res => {
			if (res.data.code == 200) {
				this.fourLevel = res.data.data;
			}
		});
	},
	methods: {
		handleRowClick (type,row) {
			if(row.goodsSoRange.length>0){
				let ids=''
				if(type==0){//商品已可见范围
					ids = row.goodsSoRange.substring(1,row.goodsSoRange.length-1)
					this.showTitle='商品已可见范围'
				}else{//审核开通的可见范围
					ids = row.applyAreaId.substring(1,row.applyAreaId.length-1)
					this.showTitle='审核开通的可见范围'
				}
				this.currentGoodsName= "商品名称："+ row.goodsName
				getOrganizationTreeNodeByIds(ids).then(res => {
					if (res.data.code == 200) {
						this.currentAreas = res.data.data;
						this.currentGoodsVis = true;
					}
				});
			}else{
				this.$message.warning('该商品未设置可见范围')
			}
			
		},
		cancel() {
			this.dialogVisibleEditArea = false;
		},
		submitEdit() {
			let data = {
				addSoRangeOrganization:this.addSoRangeOrganization.join(','),
				delSoRangeOrganization:this.delSoRangeOrganization.join(','),
				id:this.editData.goodsId
			};
			editGoodsSoRange(data).then(res=>{
				if(res.data.code==200){
					this.$message.success('修改成功')
					this.onLoad(this.page)
				}else{
					this.$message.error(res.data.message)
				}
			})
			this.dialogVisibleEditArea = false;
		},
		editArea(row) {
			console.log('row:', row);
			this.editData = row;
			this.dialogVisibleEditArea = true;
			this.getArealistFn(row.id);
		},
		handleCheckChange() {
			this.addSoRangeOrganization = []
			this.delSoRangeOrganization = []
			let res = this.$refs.tree.getCheckedNodes();
			let resHalf = this.$refs.tree.getHalfCheckedNodes();
			res.forEach(res1=>{
				this.addSoRangeOrganization.push(res1.id)
			})
			resHalf.forEach(resHalf1=>{
				this.addSoRangeOrganization.push(resHalf1.id)
			})
			let ids = []
			this.treeData.forEach(item=>{
				ids.push(item.id)
				item.childrenNodes.forEach(obj => {
					ids.push(obj.id)
					obj.childrenNodes.forEach(nodes => {
						ids.push(nodes.id)
						nodes.childrenNodes.forEach(child=>{
							ids.push(child.id)
						})
					});
				});
			})
			if(ids.length>0 &&this.addSoRangeOrganization.length>0){
				this.addSoRangeOrganization.forEach(id=>{
					var index = ids.indexOf(id); 
					if (index > -1) { 
						ids.splice(index, 1); 
					} 
				})
			}
			var index = ids.indexOf(2);
			if (index > -1) { 
				ids.splice(index, 1); 
			} 
			this.delSoRangeOrganization = ids
		},
		getArealistFn(id) {
			let data = {
				goodsCrossApplyId: id
			};
			getGoodsSoRangeTree(data).then(res => {
				if (res.data.success) {
					let goodsSoRangeIds=this.editData.goodsSoRange.split(',')
					let currentUserOrganizationId = res.data.data.currentUserOrganizationId;
					res.data.data.goodsSoRangeTree.forEach(item => {
						//一
						if (item.id == currentUserOrganizationId) {
							item.disabled = true;
							item.childrenNodes.forEach(obj => {
								//二
								obj.disabled = false;
								obj.childrenNodes.forEach(child => {
									//三
									child.disabled = false;
									child.childrenNodes.forEach(node => {
										//四
										node.disabled = false;
									});
								});
							});
						} else {
							item.disabled = true;
							item.childrenNodes.forEach(obj => {
								//二
								if (obj.id == currentUserOrganizationId) {
									obj.disabled = true;
									obj.childrenNodes.forEach(child => {
										//三
										child.disabled = false;
										child.childrenNodes.forEach(node => {
											//四
											node.disabled = false;
										});
									});
								} else {
									obj.disabled = true;
									obj.childrenNodes.forEach(child => {
										//三
										if (child.id == currentUserOrganizationId) {
											child.disabled = true;
											child.childrenNodes.forEach(node => {
												//四
												node.disabled = false;
											});
										} else {
											child.disabled = true;
											child.childrenNodes.forEach(node => {
												//四
												if (node.id == currentUserOrganizationId) {
													node.disabled = true;
												} else {
													node.disabled = true;
												}
											});
										}
									});
								}
							});
						}
					});
					setTimeout(() => {
						console.log(goodsSoRangeIds)
						let arr = [];
						goodsSoRangeIds.forEach(item=>{
							if(this.fourLevel[Number(item)]){
								arr.push(Number(item))
							}
						})
						this.treeData = res.data.data.goodsSoRangeTree;
						this.currentUserOrganizationId = currentUserOrganizationId;
						this.$refs.tree.setCheckedKeys(arr);
					}, 500);
				} else {
					this.$message.error(res.data.message);
				}
			});
		},
		searchReset() {
			this.query = {};
			this.onLoad(this.page);
		},
		//搜索
		searchChange(params, done) {
			this.page.currentPage = 1;
			this.query = params;
			this.onLoad(this.page, params, done);
		},
		currentChange(currentPage) {
			this.page.currentPage = currentPage;
		},
		sizeChange(pageSize) {
			this.page.pageSize = pageSize;
		},
		refreshChange() {
			this.onLoad(this.page);
		},
		onLoad(page, params = {}, done) {
			this.loading = true;
			getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
				if (done) {
					done();
				}
				const data = res.data;
				this.page.total = data.count;
				data.data.forEach(item => {
					let applyArea = item.applyArea.split(',');
					item.applyAreas = applyArea.join(' | ');
					// let storeArea = item.applyArea.split(',');
					// item.storeAreas = storeArea.join(' | ');
				});
				this.data = data.data;
				this.loading = false;
			});
		}
	}
};
</script>
